﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Domain.Entity.Entities;
using Microsoft.Extensions.DependencyInjection;
using SqlSugar;

namespace Infrastructure
{
    public static class SqlSugarSetup
    {
        public static void AddSqlSugarSetup(this IServiceCollection services, string? connectionString)
        {
            SqlSugarScope sqlSugar = new(new ConnectionConfig()
            {
                DbType = DbType.MySql,
                ConnectionString = connectionString,
                IsAutoCloseConnection = true,
            }, db =>
            {
                //每次上下文都会执行

                //获取IOC对象不要求在一个上下文
                //var log=s.GetService<Log>()

                //获取IOC对象要求在一个上下文
                //var appServive = s.GetService<IHttpContextAccessor>();
                //var log= appServive?.HttpContext?.RequestServices.GetService<Log>();

                db.Aop.OnLogExecuting = (sql, pars) =>
                {
                    Console.WriteLine(sql);
                };
            });
            sqlSugar.DbMaintenance.CreateDatabase();
            sqlSugar.CodeFirst.SetStringDefaultLength(200).InitTables(typeof(User));//根据types创建表
            sqlSugar.CodeFirst.SetStringDefaultLength(200).InitTables(typeof(Order));//根据types创建表
            services.AddSingleton<ISqlSugarClient>(sqlSugar);
            //services.AddSingleton<ISugarUnitOfWork<DbContext>>(it => new SugarUnitOfWork<DbContext>(sqlSugar));
        }
    }
}
